<template>
  <GlobalDrawer v-model="visible" title="我的审核记录" size="80%">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="审核状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" :value="1" />
            <el-option label="审核通过" :value="2" />
            <el-option label="审核驳回" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never" style="margin-top: 16px">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="category" label="审核类别" width="100">
          <template #default="{ row }">
            <el-tag :type="row.category === 'customer' ? 'primary' : 'success'">
              {{ row.category === 'customer' ? '客户审核' : '联系人审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customer_name" label="客户名称" min-width="150" />
        <el-table-column label="关联信息" min-width="120">
          <template #default="{ row }">
            <span v-if="row.category === 'customer'">{{ row.legal_person || '-' }}</span>
            <span v-else>{{ row.contact_name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="review_type_text" label="操作类型" width="100" />
        <el-table-column label="变更字段" min-width="200">
          <template #default="{ row }">
            <div v-if="row.change_details && row.change_details.length > 0">
              <el-tag
                v-for="(field, index) in row.change_details.slice(0, 3)"
                :key="index"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ field.field }}
              </el-tag>
              <el-tag v-if="row.change_details.length > 3" size="small" type="info">
                +{{ row.change_details.length - 3 }}
              </el-tag>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="提交时间" width="160" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">查看详情</el-button>
            <el-button v-if="row.status === 1" type="danger" link @click="handleCancel(row)">
              撤销
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="审核详情" width="70%" append-to-body>
      <div v-if="currentReview" v-loading="detailLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审核类别">
            {{ currentReview.category === 'customer' ? '客户审核' : '联系人审核' }}
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            {{ currentReview.review_type_text }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentReview.customer_name }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="currentReview.category === 'customer' && currentReview.legal_person"
            label="法人"
          >
            {{ currentReview.legal_person }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="currentReview.category === 'contact' && currentReview.contact_name"
            label="联系人"
          >
            {{ currentReview.contact_name }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ currentReview.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(currentReview.status)">
              {{ getStatusText(currentReview.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人" v-if="currentReview.reviewer_name">
            {{ currentReview.reviewer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间" v-if="currentReview.review_time">
            {{ currentReview.review_time }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 变更字段详情 -->
        <div class="field-changes" style="margin-top: 20px">
          <h4>变更字段详情</h4>
          <el-table :data="currentReview.change_details" border stripe>
            <el-table-column prop="field" label="字段名称" width="150" />
            <el-table-column label="更新前" min-width="200">
              <template #default="{ row }">
                <span v-if="row.old_value" class="old-value">{{ row.old_value }}</span>
                <span v-else class="empty-value">（空）</span>
              </template>
            </el-table-column>
            <el-table-column label="更新后" min-width="200">
              <template #default="{ row }">
                <span class="new-value">{{ row.new_value }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 审核备注 -->
        <div v-if="currentReview.review_remark" style="margin-top: 20px">
          <h4>审核备注</h4>
          <el-alert :title="currentReview.review_remark" type="info" :closable="false" />
        </div>
      </div>
    </el-dialog>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'
  import { customerApi } from '@/api/crm'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const loading = ref(false)
  const detailLoading = ref(false)
  const tableData = ref<any[]>([])
  const detailVisible = ref(false)
  const currentReview = ref<any>(null)

  const filterForm = reactive({
    status: '',
  })

  const pagination = reactive({
    current: 1,
    size: 20,
    total: 0,
  })

  // 获取审核列表
  const getReviewList = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.current,
        limit: pagination.size,
        status: filterForm.status ? Number(filterForm.status) : undefined,
      }
      const res = await customerApi.myReviews(params)
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } catch (error) {
      console.error('获取审核列表失败:', error)
      ElMessage.error('获取审核列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取状态类型
  const getStatusType = (status: number) => {
    const types: Record<number, string> = {
      1: 'warning',
      2: 'success',
      3: 'danger',
    }
    return types[status] || 'info'
  }

  // 获取状态文本
  const getStatusText = (status: number) => {
    const texts: Record<number, string> = {
      1: '待审核',
      2: '审核通过',
      3: '审核驳回',
    }
    return texts[status] || '未知'
  }

  // 查看详情
  const handleDetail = (row: any) => {
    currentReview.value = row
    detailVisible.value = true
  }

  // 撤销审核
  const handleCancel = async (row: any) => {
    try {
      await ElMessageBox.confirm(
        '确定要撤销此审核申请吗？撤销后将恢复到编辑前的原始状态。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )

      // 根据审核类别传递不同的参数
      await customerApi.cancelReview(row.id, row.category || 'customer')
      ElMessage.success('已撤销审核申请')
      getReviewList()
      emit('success')
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('撤销失败:', error)
        ElMessage.error(error.message || '撤销失败')
      }
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    getReviewList()
  }

  // 重置
  const handleReset = () => {
    filterForm.status = ''
    pagination.current = 1
    getReviewList()
  }

  // 分页大小改变
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    getReviewList()
  }

  // 当前页改变
  const handleCurrentChange = (current: number) => {
    pagination.current = current
    getReviewList()
  }

  // 监听抽屉显示状态
  watch(visible, newVal => {
    if (newVal) {
      getReviewList()
    }
  })
</script>

<style scoped>
  .filter-card {
    margin-bottom: 16px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .field-changes h4 {
    margin-bottom: 16px;
    color: #303133;
  }

  .old-value {
    color: #f56c6c;
    text-decoration: line-through;
  }

  .new-value {
    color: #67c23a;
    font-weight: bold;
  }

  .empty-value {
    color: #909399;
    font-style: italic;
  }
</style>
